package com.agent.gateway.filter;

import com.agent.commons.other.ThreadLocal;
import com.agent.commons.utils.JWTUtil;
import com.agent.commons.utils.Sm4Util;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPattern;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 *  网关拦截器
 */
@Component
public class InterceptFilter implements GlobalFilter, Ordered {
    private static final Logger log= LoggerFactory.getLogger(CrossFilter.class);
    /**
     * 放行路径白名单
     */
    private final List<String> allUrls= List.of( "/agent/user/user/**");


    public InterceptFilter() {
        log.info("✅ 拦截器初始化!");
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //  放行路径
        if("OPTIONS".equals(Objects.requireNonNull(exchange.getRequest().getMethod()).name())
                || filterUrl(exchange.getRequest().getURI().getPath())){
            log.info("放行路径:{}", exchange.getRequest().getURI());
            return chain.filter(exchange);
        }
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst("token");
        log.info("获取token:{}", token);
        log.info("获取请求路径:{}", exchange.getRequest().getURI());
        Claims claims = JWTUtil.parseJwt(token);
        if(claims == null){
            log.error("token解析失败");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //1.获取账号id
        String userIdFromToken = JWTUtil.getUserIdFromToken(token);
        //2.获取账号名
        String userNameFromToken = JWTUtil.getUserNameFromToken(token);
        //3.获取账号权限
        String userRoleFromToken=JWTUtil.getUserRoleFromToken(token);
        log.error("权限:{}",userRoleFromToken);
        log.info("用户ID:{},用户名:{}",userIdFromToken,userNameFromToken);
        //3.设置请求头，方便模块服务转发拦截
          //3.1 进行信息加密，后续拦截进行验证
        String key= Sm4Util.encrypt(userIdFromToken+"-"+userNameFromToken);
        log.info("加密后的key:{}",key);
        //5.构建新的请求
        ServerHttpRequest newRequest = exchange.getRequest().mutate().header("key", key)
                    .header("userId", userIdFromToken)
                    .header("userName", URLEncoder.encode(Objects.requireNonNull(userNameFromToken), StandardCharsets.UTF_8)
                    )
                    .header("userRole", userRoleFromToken).build();
        //请求放行
        return chain.filter(exchange.mutate().request(Objects.requireNonNull(newRequest).mutate().build()).build());
    }

    /**
     * 校验白名单路径
     * @param url
     * @return
     */
    private boolean filterUrl(String url){
        AntPathMatcher match=new AntPathMatcher();
        for(String allowUrl:allUrls){
            if(match.match(allowUrl,url)){
                return true;
            }
        }
        return false;
    }
    /**
     * 拦截器执行顺序设置
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
